package com.kfh.ybracelet.my;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.bean.ChangeNameResult;
import com.kfh.ybracelet.bean.UploadBean;
import com.kfh.ybracelet.login.LoginActivity;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.AbDateUtil;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.LogUtil;
import com.kfh.ybracelet.widget.ActionSheetDialog;
import com.kfh.ybracelet.widget.CircleImageView;
import com.kfh.ybracelet.widget.MyDatePicker;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONException;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 我的信息修改页面
 * Created by Aaron on 15/8/11.
 */
public class SettingActivity extends BaseActivity {

    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE = 1041;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE = 1042;
    /**
     * 裁剪
     */
    public static final int PHOTO_RESOULT = 1043;
    public final String IMAGE_UNSPECIFIED = "image/*";
    /*拍照的文件保存的位置*/
    private File currentFile;
    //    private ProgressDialog pdialog;
    //修改我的姓名Code
    private static final int MODIFY_MY_NAME_CODE = 10000;
    //    private static final int MODIFY_MY_BIRTHDAY_CODE = 10001;
    private static final int MODIFY_MY_PHONE_CODE = 10002;
    private static final int CHANGE_SEX_CODE = 10015;
    //    private static final int MODIFY_MY_BABYINVITATIONCODE_CODE = 10004;
    private TextView tv_name;
    private TextView tv_sex;
    private TextView tv_birthday;
    private TextView tv_tel;
    //    private TextView tv_invite_code;
    private Intent mIntent;
    private CircleImageView iv_photo;
    private String imageUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my_info);

        initWidget();
        setData();

        imageUrl = sp.getString(Constant.USERIMG, "");

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 设置数据
     */
    private void setData() {

        tv_name.setText(sp.getString(Constant.NICKNAME, ""));

        if (Constant.FREMAL.equals(sp.getString(Constant.SEX, ""))) {
            tv_sex.setText("女");
        } else {
            tv_sex.setText("男");
        }

        tv_birthday.setText(sp.getString(Constant.BIRTHDAY, ""));
        tv_tel.setText(sp.getString(Constant.MOBILE, ""));

        Glide.with(this)
                .load(sp.getString(Constant.USERIMG, ""))
                .dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE).fitCenter()
                .placeholder(R.mipmap.temp_pic)
                .into(iv_photo);

    }

    private void upDateUserInfo() {

        final JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("nickName", tv_name.getText().toString().trim());
        j.put("birthDay", tv_birthday.getText().toString().trim());
        j.put("sex", tv_sex.getText().toString().trim());
        j.put("userImg", imageUrl);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.WEB_ROOT + Constant.UPDATEUSERINFO, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                LogUtil.e("TAG", "返回的json===:" + response);

                try {
                    org.json.JSONObject result = new org.json.JSONObject(response);

                    if (result.getInt("code") == Constant.STATUS_SUCCESS) { //code==0 成功
                        try {

                            ChangeNameResult changeNameResult = JSONObject.parseObject(response, ChangeNameResult.class);

                            if (changeNameResult.code == Constant.STATUS_SUCCESS) {
                                SharedPreferences.Editor edit = sp.edit();
                                edit.putString(Constant.NICKNAME, tv_name.getText().toString().trim());
                                edit.putString(Constant.SEX, tv_sex.getText().toString().trim());
                                edit.putString(Constant.BIRTHDAY, tv_birthday.getText().toString().trim());
//                                edit.putString(Constant.MOBILE, tv_tel.getText().toString().trim());
                                edit.apply();
                            } else {

                                updateFail();

                                showToast(Constant.showErrorMsg(changeNameResult.code, SettingActivity.this));

                            }
                        } catch (Exception e) {

                            updateFail();

                            e.printStackTrace();
                            showToast(Constant.NODATA);

                        }

                    } else if (result.getInt("code") == Constant.FA_TOKEN_TIMEOUT_ERROR) { //登录超时

                        Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
                        intent.putExtra("isAutoLogin", false);
                        startActivity(intent);

                    } else {            //其他错误
                        Toast.makeText(SettingActivity.this, result.getString("code_msg"), Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(SettingActivity.this, "数据格式错误", Toast.LENGTH_SHORT).show();

                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                updateFail();
                showToast("网络错误");
            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", j.toJSONString());
                return param;
            }

        };

        //把请求加入队列
        mApplication.addToRequestQueue(stringRequest, getClass().getName());

    }

    /**
     * 更新失败
     */
    private void updateFail() {

        tv_name.setText(sp.getString(Constant.NICKNAME, ""));
        tv_birthday.setText(sp.getString(Constant.BIRTHDAY, ""));
        tv_sex.setText(sp.getString(Constant.SEX, ""));

    }

    private void initWidget() {

        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.my_setting));

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);

        iv_photo = (CircleImageView) findViewById(R.id.iv_photo);

        RelativeLayout rl_head_pic = (RelativeLayout) findViewById(R.id.rl_head_pic);
        RelativeLayout rl_name = (RelativeLayout) findViewById(R.id.rl_name);
        RelativeLayout rl_sex = (RelativeLayout) findViewById(R.id.rl_sex);
        RelativeLayout rl_birthday = (RelativeLayout) findViewById(R.id.rl_birthday);
//        RelativeLayout rl_tel = (RelativeLayout) findViewById(R.id.rl_tel);
        RelativeLayout rl_modify_code = (RelativeLayout) findViewById(R.id.rl_modify_code);

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_sex = (TextView) findViewById(R.id.tv_sex);
        tv_birthday = (TextView) findViewById(R.id.tv_birthday);

        tv_tel = (TextView) findViewById(R.id.tv_tel);
//        tv_invite_code = (TextView) findViewById(R.id.tv_invite_code);

        iv_left.setOnClickListener(this);
        rl_head_pic.setOnClickListener(this);
        rl_name.setOnClickListener(this);
        rl_sex.setOnClickListener(this);
        rl_birthday.setOnClickListener(this);
//        rl_tel.setOnClickListener(this);
        rl_modify_code.setOnClickListener(this);

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:
                finish();
                break;
            case R.id.rl_head_pic://头像

                showChoose();

                break;
            case R.id.rl_name://姓名

                mIntent = new Intent(this, ModifyNameActivity.class);
                startActivityForResult(mIntent, MODIFY_MY_NAME_CODE);
                break;

            case R.id.rl_sex://性别

                mIntent = new Intent(this, ChangeSexActivity.class);
                startActivityForResult(mIntent, CHANGE_SEX_CODE);
                break;

            case R.id.rl_birthday://生日
                String birthday = sp.getString(Constant.BIRTHDAY, "");
                Date date = null;

                if (!CommonUtils.isNull(birthday)) {
                    date = AbDateUtil.getDateByFormat(birthday, AbDateUtil.DATEFORMATYMD);
                }

                Calendar c = Calendar.getInstance();
                if (date != null) {
                    c.setTime(date);
                }

                new MyDatePicker(this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                                          int dayOfMonth) {

                        String month = (monthOfYear + 1) < 10 ? "0" + (monthOfYear + 1) : (monthOfYear + 1) + "";
                        String day = dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth + "";

                        tv_birthday.setText(year + "-" + month + "-" + day);

                        upDateUserInfo();

                    }

                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
                        c.get(Calendar.DAY_OF_MONTH)).show();

                break;

            case R.id.rl_modify_code://修改密码

                mIntent = new Intent(this, ModifyCodeActivity.class);
                startActivity(mIntent);
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case MODIFY_MY_NAME_CODE://修改我的姓名

                if (data == null)
                    return;

                tv_name.setText(data.getStringExtra("modifyname"));
                upDateUserInfo();

                break;

            case CHANGE_SEX_CODE://修改我的性别

                if (data == null)
                    return;
                tv_sex.setText(data.getStringExtra("modifySex"));
                upDateUserInfo();

                break;

            case MODIFY_MY_PHONE_CODE://修改我的电话

                if (data == null)
                    return;

                tv_tel.setText(data.getStringExtra("modifyphone"));
                upDateUserInfo();

                break;

            case TAKE_PHOTO_CODE:       //拍照

                //上传图片
                if (currentFile != null && currentFile.exists()) {

                    //裁剪图片
                    startPhotoZoom(Uri.fromFile(currentFile));
                }

                break;

            case PHOTO_ALBUM_CODE:       //选择照片

                if (data == null)
                    return;

                Uri selectedImage = data.getData();
                if (selectedImage == null) {
                    showToast("图片读取失败");
                    return;
                }

                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();

                //裁剪图片
                startPhotoZoom(Uri.fromFile(new File(picturePath)));

                break;

            case PHOTO_RESOULT: //裁剪图片

                if (data == null)
                    return;

                Bundle extras = data.getExtras();

                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    getUploadToken(CommonUtils.compressByte(photo));
                }

                break;
        }

    }

    /**
     * 裁剪图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_RESOULT);
    }

    private void getUploadToken(final byte[] bytes) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("加载中...", SettingActivity.this, Constant.WEB_ROOT + Constant.UPLOADTOKEN,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        LogUtil.e("tag", "返回的token==" + str);

                        final UploadBean uploadBean = JSONObject.parseObject(str, UploadBean.class);

                        if (uploadBean.code == Constant.STATUS_SUCCESS) {

                            UploadManager uploadManager = new UploadManager();

                            uploadManager.put(bytes, uploadBean.path, uploadBean.token,
                                    new UpCompletionHandler() {
                                        @Override
                                        public void complete(String s, ResponseInfo responseInfo, org.json.JSONObject jsonObject) {

                                            if (responseInfo.isOK()) {

                                                imageUrl = uploadBean.domain + uploadBean.path;
//
                                                Glide.with(SettingActivity.this)
                                                        .load(imageUrl)
                                                        .dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE).fitCenter()
                                                        .placeholder(R.mipmap.temp_pic)
                                                        .into(iv_photo);

                                                sp.edit().putString(Constant.USERIMG, imageUrl).apply();

                                                upDateUserInfo();

                                            } else {
                                                showToast("图片上传失败");
                                            }

                                        }

                                    }, null);

                        } else {
                            showToast(Constant.showErrorMsg(uploadBean.code, SettingActivity.this));
                        }

                    }
                }, null);

    }

    /**
     * 弹出选择照片的对话框
     */
    @Deprecated
    protected void showChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 拍照
                                getTakePhoto();

                            }

                        })
                .addSheetItem("去相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 从相册中选择
                                getFromPhotoAlbum();
                            }
                        }).show();

    }

    /**
     * 拍照
     */
    private void getTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + Constant.PHOTO_PATH;
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE);
    }

    /**
     * 从相册中选择
     */
    private void getFromPhotoAlbum() {

        Intent mIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(mIntent, PHOTO_ALBUM_CODE);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mApplication.cancelPendingRequests(getClass().getName());
    }

}
